package cn.getech.data.metadata.controller.blood;

import cn.getech.data.intelligence.common.exception.RRException;
import cn.getech.data.intelligence.common.utils.BaseRes;
import cn.getech.data.metadata.model.excel.*;
import cn.getech.data.metadata.service.CollectionBloodService;
import cn.getech.system.center.annotation.SysLog;
import cn.getech.system.center.constant.OperationModulesEnum;
import cn.getech.system.center.constant.OperationTypeEnum;
import cn.getech.system.center.constant.module.ModuleEnum;
import cn.getech.system.center.utils.ShiroUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;


/**
 * @description: 血缘接口
 * @author: wangzhaowen：kiss
 * @create: 2020/9/30 11:00
 * @version: 2020/9/30
 **/
@Slf4j
@Api(value = "采集任务", tags = {"采集任务模块"})
@RestController
@RequestMapping("md/blood")
public class CollectionBloodController {
    @Autowired
    private CollectionBloodService collectionBloodService;


    @ApiOperation("导入")
    @PostMapping("/check") // /data-metadata/md/blood/check
    public BaseRes checkFile( @RequestParam(value = "file") MultipartFile file) {
        ExcelReader excelReader = null;

        if (file == null) {
            return BaseRes.error("任务文件不能为空");
        }
        try {
            JSONObject res = new JSONObject();
            BloodTableFieldListener tableFieldListener = new BloodTableFieldListener(collectionBloodService, res, true);
            excelReader = EasyExcel.read(file.getInputStream(), CollectionBloodExcel.class,
                    tableFieldListener).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            return BaseRes.okWithData(res);
        } catch (RRException e) {
            log.error("导入错误:", e);
            return BaseRes.error(e.getMsg());
        } catch (Exception e) {
            log.error("导入错误:", e);
            if (e.getCause() != null) {
                return BaseRes.error(e.getCause().getMessage());
            } else {
                return BaseRes.error("excel文件解析失败");
            }
        } finally {
            if (excelReader != null) {
                excelReader.finish();
            }
        }

    }

    @ApiOperation("导入")
    @PostMapping("/import") // /data-metadata/md/blood/import
    @SysLog(value="血缘导入",type= OperationTypeEnum.RUNCODE,
            modulesType = OperationModulesEnum.DATAMETADATACODE,platformModuleType = ModuleEnum.METADATA_LIST_MODULE_CODE)
    public BaseRes importFile(@RequestParam(value = "file") MultipartFile file) {
        ExcelReader excelReader = null;
        if (file == null) {
            return BaseRes.error("任务文件不能为空");
        }
        try {
            JSONObject res=new JSONObject();
            Long userId = ShiroUtils.getUserId();
            Integer tenantId = ShiroUtils.getTenantId();
            BloodTableFieldListener tableFieldListener = new BloodTableFieldListener(
                    collectionBloodService,res,userId,tenantId);
            excelReader = EasyExcel.read(file.getInputStream(), CollectionBloodExcel.class,
                    tableFieldListener).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            if (res.getString("error_log") != null) {
                return BaseRes.error(res.getString("error_log"));
            }
            return BaseRes.okWithData(res);
        } catch (RRException e) {
            return BaseRes.error(e.getMsg());
        } catch (Exception e) {
            log.error("导入错误:", e);
            return BaseRes.error("excel文件解析失败");
        } finally {
            if (excelReader != null) {
                excelReader.finish();
            }
        }
    }

    @ApiOperation("失败文件")
    @GetMapping("/fail/file") // /data-metadata/md/blood/fail/file
    @SysLog(value="血缘失败文件下载",type= OperationTypeEnum.DOWNLOADCODE,
            modulesType = OperationModulesEnum.DATAMETADATACODE,platformModuleType = ModuleEnum.METADATA_LIST_MODULE_CODE)
    public BaseRes failFile(HttpServletResponse response) {
        String fileName = "leadingResult";
        response.setHeader("Content-Type", "application/octet-stream");
        ExcelWriter excelWriter = null;
        try {
            // 清空response
            response.reset();
            fileName = String.format("%s.xlsx", URLEncoder.encode(fileName, "utf-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("filename", fileName);
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            ServletOutputStream os = response.getOutputStream();
            Long userId = ShiroUtils.getUserId();
            List<CollectionBloodExcelError> data = BloodTableFieldListener.getFailList(userId);
            excelWriter = EasyExcel.write(os,
                    CollectionBloodExcelError.class)
                    .registerWriteHandler(new MySheetWriteHandler(CollectionBloodExcelError.class))
                    .registerWriteHandler(new MyCellWriteHandler(CollectionBloodExcelError.class))
                    .build();
            WriteSheet sheet = EasyExcel.writerSheet().build();
            excelWriter.write(data, sheet).finish();
        } catch (IOException e) {
            return BaseRes.error("模板文件错误");
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
        return null;
    }


    @ApiOperation("下载模板")
    @GetMapping("/temp/file") // /data-metadata/md/blood/temp/file
    @SysLog(value="血缘模板下载",type= OperationTypeEnum.DOWNLOADCODE,
            modulesType = OperationModulesEnum.DATAMETADATACODE,platformModuleType = ModuleEnum.METADATA_LIST_MODULE_CODE)
    public BaseRes tempFile(HttpServletResponse response) {
        String fileName = "模板文件" + System.currentTimeMillis();
        response.setHeader("Content-Type", "application/octet-stream");
        ExcelWriter excelWriter = null;
        try {
            // 清空response
            response.reset();
            fileName = String.format("%s.xlsx", URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("filename", fileName);
            response.setContentType("application/octet-stream");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setCharacterEncoding("UTF-8");
            ServletOutputStream os = response.getOutputStream();
            excelWriter = EasyExcel.write(os,
                    CollectionBloodExcel.class)
                    .registerWriteHandler(new MySheetWriteHandler(CollectionBloodExcel.class))
                    .registerWriteHandler(new MyCellWriteHandler(CollectionBloodExcel.class))
                    .build();
            WriteSheet sheet = EasyExcel.writerSheet().build();
            excelWriter.write(null, sheet).finish();
        } catch (IOException e) {
            return BaseRes.error("模板文件错误");
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
        return null;
    }


}
